import React from 'react';
import { connect } from 'react-redux';

import { TeacherFilter } from '../../components/smart/filter';
import ChartGroup from '../../components/smart/ChartGroup';
import PieChart from '../../components/dump/charts/PieChart';

import Tabs from 'material-ui/lib/tabs/tabs';
import Tab from 'material-ui/lib/tabs/tab';
import FlatButton from 'material-ui/lib/flat-button';

import { ENUM_VIEW } from '../../../schema/constants';

import { 
	getSourceDistributionData } 
	from '../../actions/examination-analysis/sourceDistributionAction';
import { setCondition } from '../../actions/fixup-work/conditionAction';

import omit from 'lodash/object/omit';
import moment from 'moment';
import { DATE_FORMATTER } from '../../../schema/constants';

function mapStateToProps(state) {
	return {
		sourceDistribution: state.sourceDistribution,
		condition: state.chart.condition
	};
}

function getData(condition, state) {
	return getSourceDistributionData({
		condition: omit(condition, 'dataOptions'),
		...state
	});
};

export class SourceDistribution extends React.Component {
	state = {
		currentTimeUnit: ENUM_VIEW.DAY
	};

	constructor(props) {
		super(props);
	}

	// 点击高级筛选条件查询按钮
	handleSearch = () => {
		let { dispatch, condition } = this.props;

		// get data
		dispatch(getData(condition, this.state));
	};

	// 处理日期范围变化
	handleDateRangeChange = (startDate, endDate) => {
		let { dispatch } = this.props;

		let action = setCondition('startDate', moment(startDate).format(DATE_FORMATTER));
		dispatch(action);

		action = setCondition('endDate', moment(endDate).format(DATE_FORMATTER));
		dispatch(action);

		// get data
		setTimeout(() => {
			let { condition } = this.props;
			dispatch(getData(condition, this.state));
		}, 0);
	};

	// 时间颗粒度
	handleTimeUnitChange = (option) => {
		let { dispatch, condition } = this.props;

		this.setState({
			currentTimeUnit: option
		}, () => {
			dispatch(getData(condition, this.state));
		});
	};

	componentWillMount() {
		let { dispatch, condition } = this.props;
		dispatch(getData(condition, this.state));
	}

	render() {
		let { sourceDistribution, condition } = this.props;
		let { startDate, endDate } = condition;

		let { currentTimeUnit } = this.state;

		return (
			<div className='panel'>
				<TeacherFilter onSearch={this.handleSearch} />
				<ChartGroup
					onDateRangeChange={this.handleDateRangeChange}
					startDate={startDate}
					endDate={endDate}>
					<Tabs
						onChange={this.handleTimeUnitChange}
						value={currentTimeUnit}>
						<Tab label='日' value={ENUM_VIEW.DAY}></Tab>
						<Tab label='周' value={ENUM_VIEW.WEEK}></Tab>
						<Tab label='月' value={ENUM_VIEW.MONTH}></Tab>
					</Tabs>
					<div className='chart'>
						<PieChart title={`各来源布置题目次数分布`}
							subtitle=''
							dataSource={sourceDistribution.distributionData.data} />
					</div>
				</ChartGroup>
			</div>
		);
	}
}

export default connect(
	mapStateToProps,
	// Implement map dispatch to props
)(SourceDistribution)
